<?php
/**
 * IndexController - The default controller class
 *
 * @author
 * @version
 */
require_once 'Zend/Controller/Action.php';

class PromotionController extends App_Zend_Controller_Action_Shop
{
	private $_itemidArr = array();
	
	public function init()
	{
		parent::init();
	}
	
	public function indexAction()
	{
		$this->view->styleName = "product";
		$this->getHelper('Fenlei')->getCategories();
		
		$itemids = $this->getRequest()->getParam('itemid', 0);
		$resultIdArray = explode('|', base64_decode($itemids));
		
		$myCache = Zend_Registry::get('myCache');
		$itemMap = CCache::getCombinlistItemMap();
		$resultItemArray = array();
		$canBuy = true;
		foreach($resultIdArray as $key => $v){
			if($itemMap[$v]){
				$resultItemArray[] = $itemMap[$v];
			}else{
				$canBuy = false;
				$item = new CItem();
        		$itemArray = $item->getDetail($v,'product');
				if($itemArray && count($itemArray)>0){
					$resultItemArray[] = $itemArray[0];
				}else{
					$resultItemArray[] = null;
				}
			}
		}
		$this->view->canBuy = $canBuy;
		
		$price=new CProductPrice();
		$resultPriceArray = array();
		$resultImgArray = array();
		
		$tmpArr = array();
		$tmpImgArr = array();
		$priceArrays = array();
		foreach ($resultItemArray as $k=>$_v){
			
			//if (!$priceArray = $myCache->load('price_' . $_v['itemid'])) {
				$priceArray = $price->getAllPrice($_v['itemid']);
			//}
			$priceArrays[] = $priceArray;
			//$myCache->save($priceArray, 'price_' . $_v['itemid']);
			$tmpImgArr[] = $_v['cut_url'];
			foreach ($priceArray as $__v) {
				//if ($__v['max_counts'] < 4) {
					if (isset($tmpArr['price_org'])) {
						$tmpArr['price_org'] += $__v['net_price'];
					} else {
						$tmpArr['price_org'] = $__v['net_price'];							
					}
					break;
				//}
			}
			foreach ($priceArray as $__v) {
				if ($__v['min_counts'] <= 4 && $__v['max_counts'] >= 4) {
					if (isset($tmpArr['price_pack'])) {
						$tmpArr['price_pack'] += $__v['net_price'];
					} else {
						$tmpArr['price_pack'] = $__v['net_price'];							
					}
					break;
				}
			}		
		}
		$this->view->priceArray = $priceArrays;
		
		$patternSizeArr = array();
		$attachment=new CAttachment();
		$attachmentArr = array();
		foreach ($resultItemArray as $v) {
			$pattern_size=unserialize($v['product_pattern']);
            $pattern_size_stock=unserialize($v['product_pattern_stock']);
            if (is_array($pattern_size_stock)) {
            	$new_pattern_size_stock = array();
	            for($i = 0; $i < count($pattern_size); $i++) {
					if (isset($pattern_size_stock[$pattern_size[$i]]) && $pattern_size_stock[$pattern_size[$i]] > 0) {
						$new_pattern_size_stock[] = $pattern_size[$i];
					}
	            }
            } else {
            	$new_pattern_size_stock = $pattern_size;
            }
            $patternSizeArr[] = is_array($new_pattern_size_stock)?$new_pattern_size_stock:array();
            
            $attachmentArr[] = $attachment->getAttachments($v['itemid'] ,'cut_url !=""');
          
		}
		
		$this->view->attachmentArray = $attachmentArr;
		
		$this->view->pattern_size = $patternSizeArr;
		
		$this->view->price = $tmpArr;
		$this->view->thumb = implode('|', $tmpImgArr);	
		
		$this->view->itemDetailArray = $resultItemArray;
		
		//随机爬虫产品
		$crawlSearchKey = $resultItemArray[0]['subject'].' '.$resultItemArray[1]['subject'].' '.$resultItemArray[2]['subject'].' '.$resultItemArray[3]['subject'];
		$search = new CSearch();
		$crawlIds = $search->searchCrawlAny($crawlSearchKey,300);
		$myrandom = new CMyRandom();
		$citem = null;
		if(count($crawlIds)==0){
			$maxCrawlId = CCache::getCrawlMaxId()+1;
			while($citem == null){
				$index = $myrandom->getRandomNumber($crawlSearchKey,$maxCrawlId);
				$crawl = new CCrawl();
				$citem = $crawl->getCrawlItem($index);
			}
		}else{
			$index = $myrandom->getRandomNumber($crawlSearchKey,count($crawlIds));
			$crawid = $crawlIds[$index];
			$crawl = new CCrawl();
			$citem = $crawl->getCrawlItem($crawid);
		}
		$this->view->crawlItem = $citem;
		
		$title=$resultItemArray[0]['subject'].' and '.$citem['name'];
		
		$title = str_ireplace(array('Soccer','Jersey','Shirt','Replica','whole','kit','football'),'',$title);
		$title = preg_replace(array('/\s\s+/','/\s,/'),array(' ',','),$title);
		$title = $title.' soccer jersey';
		
		$titleKeywords = array('Up to ${persent}% off','${persent}% off','${persent}% off +','${persent}% off free shipping','${persent}% off + free shipping','free shipping','Up to ${persent}% off free shipping');
		$myRandom = new CMyRandom();
		$titleKeyword = $titleKeywords[$myRandom->getRandomNumber($crawlSearchKey.'titleKeywords',count($titleKeywords))];
		if(strpos($titleKeyword,'${persent}')!==false){
			$discountNum = $myRandom->getRandomNumber($crawlSearchKey.'persent',80)+2;
			$titleKeyword = str_replace('${persent}',$discountNum,$titleKeyword);
		}
		$title = $titleKeyword.' '.$title;
		$this->view->titleKeyword = $titleKeyword;
		
		if($resultItemArray[0]['description'] != ''){
			$desc=$resultItemArray[0]['description'].',';
		}
		if($resultItemArray[1]['description'] != ''){
			$desc.=$resultItemArray[1]['description'].',';
		}
		if($resultItemArray[2]['description'] != ''){
			$desc.=$resultItemArray[2]['description'].',';
		}
		if($resultItemArray[3]['description'] != ''){
			$desc.=$resultItemArray[3]['description'];
		}
		
//		if($resultItemArray[0]['keywords'] != ''){
//			$keywords=$resultItemArray[0]['keywords'].',';
//		}
//		if($resultItemArray[1]['keywords'] != ''){
//			$keywords.=$resultItemArray[1]['keywords'].',';
//		}
//		if($resultItemArray[2]['keywords'] != ''){
//			$keywords.=$resultItemArray[2]['keywords'].',';
//		}
//		if($resultItemArray[3]['keywords'] != ''){
//			$keywords.=$resultItemArray[3]['keywords'];
//		}
		$keyArr = array();
		$keyModel = new CKeywords();
 		$tmp = $keyModel->getRelateKey($resultItemArray[0]['productid']);
 		$i = 0;
 		foreach ($tmp as $v) {
 			if ($i>2) {
 				break;
 			}
 			$keyArr[] = $v['keywords'];
 			$i++;
 		}
		$tmp = $keyModel->getRelateKey($resultItemArray[1]['productid']);
		$i = 0;
 		foreach ($tmp as $v) {
 			if ($i>2) {
 				break;
 			}
 			$keyArr[] = $v['keywords'];
 		}
		$tmp = $keyModel->getRelateKey($resultItemArray[2]['productid']);
 		$i = 0;
		foreach ($tmp as $v) {
 			if ($i>2) {
 				break;
 			}
 			$keyArr[] = $v['keywords'];
 		}
		$tmp = $keyModel->getRelateKey($resultItemArray[3]['productid']);
 		$i = 0;
		foreach ($tmp as $v) {
 			if ($i>2) {
 				break;
 			}
 			$keyArr[] = $v['keywords'];
 		}
 		
 		$keyArr = array_unique($keyArr);
 		
		$tmp = array();
		$i = 0;
		foreach ($keyArr as $v) {
			if ($i>8) {
				break;
			}
			$tmp[] = $v;
			$i++;
		}
 	
		$this->view->webSiteTitle = $title;
        $this->view->webSiteDescription = str_replace("\"","",$desc);
        $this->view->webSiteKeywords = implode(',', $tmp);

        if ($this->view->webSiteDescription == '') {
        	$this->view->webSiteDescription = $this->view->webSiteTitle . ', soccer jersey shirt online sale';
        }
		
		$keyModel = new CKeywords();
		$randomKeywords = $keyModel->getRandomKeywords(10,$title);
		$this->view->randomKeywords = $randomKeywords;
        
		$cart = new CCart();       
        $member = new CMember();
        if (!$member->isUser($this->getRequest()->getModuleName(),$this->getRequest()->getControllerName())||$_COOKIE[COOKIE_PRE.'member_type']!='buyer'){
        	//未登录
        	$sessionHash = $_COOKIE[COOKIE_PRE.'product_buy_session'];
	        if($sessionHash != '') {
				$cartStr = $cart->getCartStr($sessionHash);
				if ($cartStr) {	           		
				} else {
					$sessionHash = $cart->sessionHash();
				}			
	        } else {
	        	$sessionHash = $cart->sessionHash();
	        }
	        setcookie(COOKIE_PRE.'product_buy_session', $sessionHash, time()+3600*24*180,'/');
        }
        
        /*属性筛选*/
		$attr = new CAttr();
        $categoryAttr = $attr->getByType(1);	
        $brandAttr = $attr->getByType(2);	
        $playerAttr = $attr->getByType(3);
        
        $this->view->categoryAttr=$categoryAttr;
        $this->view->brandAttr=$brandAttr;
        $this->view->playerAttr = $playerAttr;
        
        $this->view->isshowchoose = 1;
	}
	
	public function addtocartAction()
	{
		$this->_helper->viewRenderer->setNoRender();
        $this->getHelper ('layout')->disableLayout ();
        $itemids = $this->getRequest()->getParam('itemids');

        foreach ($itemids as $v) {
	        $pattern_name = $this->_request->getParam('pattern_name_' . $v);
	   
	        $pattern_size=$this->_request->getParam('pattern_size_' . $v);
	            
	        $select_Original=$this->_request->getParam('select_Original_' . $v);
	        $countsArray=$this->_request->getParam('counts_' . $v);
	       
	        $printMesg = $this->_request->getParam('printMesg');
	      
	        $print_meno = '';	                	
	        $counts=0;
	        $patternContent='';
	        $product = new CProduct();
	        $itemid =$v;
	        
	        /**
	         * 购物车行为跟踪
	         */
	        $productLog = new CProductlog();
	        $productLog->insert(array('uid'=>$_COOKIE[COOKIE_PRE.'uid'], 'itemid'=>$itemid, 'ip'=>$_SERVER['REMOTE_ADDR'], 'addtime'=>date('Y-m-d H:i:s', time())));
	       /**
	        * end
	        */
	        
	        for($i=0;$i<count($countsArray);$i++) {
	            if($countsArray[$i]!=0) {
	                $counts+=$countsArray[$i];
	                $patternContent.=$pattern_size[$i].':'.$countsArray[$i];
	                //不必更新，只要知道库存多少
	                $stock = $product->getPatternStock($pattern_size[$i], $countsArray[$i], $itemid);
	                if ($stock > 0) {
	                	$patternContent .= ', ';
	                } else {
	                	$patternContent .= ',<font style=\'color: red\'>[This size sold out, please wait for 5-7 days]<\/font>, ';
	                }
	            }
	        }   
	        
	        if ($counts == 0) {
	        	continue;
	        }
	        
	        $cookieArray=array(
	        	$itemid=>array(
	        		'pattern_name'=>$pattern_name,
	        		'counts'=>$counts,
	        		'pattern_size'=>$patternContent,
	        		'printMesg'=>$print_meno . $printMesg,        		
	        		'badge_patch_amount'=>0,
	        		'badge_patch_money'=>0
	        	)
	        );
			
	        
	        
	        //if ($badgepatchFlag) {
	        	//$cookieArray[$itemid]['BadgePatch'] = 'Yes';
	        //} else {
	        	$cookieArray[$itemid]['BadgePatch'] = 'No';
	        //}
	        
	       // if ($myOrigialAmount > 0) {
	        //	$cookieArray[$itemid]['originalname_num'] = $myOrigialAmount;
	        //	$cookieArray[$itemid]['originalprintAmounts'] = $myOrigialAmount;
	       // } else {
	        	$cookieArray[$itemid]['originalname_num'] = '';
	        	$cookieArray[$itemid]['originalprintAmounts'] = '';
	        //}
	    	//if ($myPrintAmount > 0) {
	        //	$cookieArray[$itemid]['name_num'] = $myPrintAmount;
	        //	$cookieArray[$itemid]['printAmounts'] = $myPrintAmount;
	       // } else {
	        	$cookieArray[$itemid]['name_num'] = '';
	        	$cookieArray[$itemid]['printAmounts'] = '';
	        //} 
	        $sessionHash = $_COOKIE[COOKIE_PRE.'product_buy_session'];
			$cart = new CCart();
	        $shoppingArray=array();
	        $member = new CMember();
	        if (!$member->isUser($this->getRequest()->getModuleName(),$this->getRequest()->getControllerName())||$_COOKIE[COOKIE_PRE.'member_type']!='buyer'){
	        	//未登录
		        if($sessionHash != '') {
					$cartStr = $cart->getCartStr($sessionHash);
					if ($cartStr) {
		           		$shoppingArray=json_decode(stripslashes($cartStr),true);
					} 		
		        } else {
		        	$sessionHash = $cart->sessionHash();
		        }
	        } else {
	        	//登录
	        	$sessionHash = $cart->sessionHash();
	        	$cartStr = $cart->getCartStrByUid($_COOKIE[COOKIE_PRE.'uid']);
	        	if ($cartStr) {
		           	$shoppingArray=json_decode(stripslashes($cartStr),true);
				}
	        }
	        
	
	        if(isset($cookieArray[$itemid])) {
	            $shoppingArray[$itemid]=$cookieArray[$itemid];
	        }
	       
	        $cartStr = json_encode($shoppingArray);
	        
	        if (!$member->isUser($this->getRequest()->getModuleName(),$this->getRequest()->getControllerName())||$_COOKIE[COOKIE_PRE.'member_type']!='buyer'){
	        	//未登录
	        	$row = array('cart_str'=>addslashes($cartStr), 'expires'=>time()+3600*24*180);
	        	setcookie(COOKIE_PRE.'product_buy_session', $sessionHash, time()+3600*24*180,'/');
				$cart->setCartStr($sessionHash, $row);
	        } else {
	        	//登录
	        	$row = array('cart_session_id'=>$sessionHash, 'cart_str'=>addslashes($cartStr), 'expires'=>time()+3600*24*180, 'uid'=>$_COOKIE[COOKIE_PRE.'uid']);
	        	$cart->setCartStrByUid($_COOKIE[COOKIE_PRE.'uid'], $row);
	        }
        }
        
        $this->_redirect(MY_URL.'/product-showitem');
	}
	
	public function mergeAction()
	{		
		$this->getHelper('viewRenderer')->setNoRender();
		$this->getHelper('layout')->disableLayout();
		
		
		$fromImg = $this->getRequest()->getParam('path', '');
		
		if (empty($fromImg)) {
			exit();
		}
		
		$fromImg = explode('|', $fromImg);
		$img=new CClsImage();
		$path = new CPath();
		foreach ($fromImg as &$v) {	
			$to = '';
			$to = str_replace('cut_item_img', 'new_cut_item_img',$v);		
			//$v = $path->toAbsoluteRootPath(str_replace('cut_item_img', 'new_cut_item_img',$v));
			if(!file_exists(MY_ROOT . "/" . $to)){
				//exit();
				$toPathArr = pathinfo($to);
        		$img->make_thumb2(MY_ROOT . "/" .$v,122,0,MY_ROOT . "/" . $toPathArr['dirname'] . '/', '', $toPathArr['filename']);
			}
			$v = $to;
		}
		
		$image0 = new Gmagick($fromImg[0]);
		//$image0->thumbnailImage(122, 122); 
		
		$image1 = new Gmagick($fromImg[1]);
		//$image1->thumbnailImage(122, 122); 
		
		$image2 = new Gmagick($fromImg[2]);
		//$image2->thumbnailImage(122, 122); 
		
		$image3 = new Gmagick($fromImg[3]);
		//$image3->thumbnailImage(122, 122); 
		
		$image = new Gmagick();
		$image->newImage(250, 250, 'white', 'jpg');
		
		$image->compositeImage($image0, Gmagick::COMPOSITE_OVER, 2, 2);
		$image->compositeImage($image1, Gmagick::COMPOSITE_OVER, 125, 2);
		$image->compositeImage($image2, Gmagick::COMPOSITE_OVER, 2, 125);
		$image->compositeImage($image3, Gmagick::COMPOSITE_OVER, 125, 125);
		header("Content-Type: image/jpg"); 
		$seconds_to_cache = 3600 * 24 * 360;
		$ts = gmdate("D, d M Y H:i:s", time() + $seconds_to_cache) . " GMT";
		header("Expires: $ts");
		header("Pragma: cache");
		header("Cache-Control: max-age=$seconds_to_cache");
		echo $image; 
	}
	
	public function crawldetailAction(){
		$this->view->styleName = "product";
		$this->getHelper('Fenlei')->getCategories();
		
		$id = $this->getRequest()->getParam('id', 0);
		$crawl = new CCrawl();
		$crawlItem = $crawl->getCrawlItem($id);
		try{
			$crawlItem['description'] = preg_replace('/(<a[^>]*>[^<]*<\/a>)|(Lamentamos[\s\S]+?producto.)/','',$crawlItem['description']);
		}catch(Exception $e){
			$e->getTraceAsString();
		}
		$this->view->crawlItem = $crawlItem;
		
		$this->view->isCrawlitem = 1;
		
		//L　SEARCH
		$myCache=Zend_Registry::get('myCache');
		$cacheId=md5($crawlItem['name']);
		$result=$myCache->load($cacheId);
		$maxScore=$myCache->load($cacheId.'_score');
		if(!$result || !$maxScore){
			$index=Zend_Search_Lucene::open(MY_ROOT."/indexdata/index");
			Zend_Search_Lucene_Search_QueryParser::setDefaultOperator(Zend_Search_Lucene_Search_QueryParser::B_OR);
			$query=Zend_Search_Lucene_Search_QueryParser::parse(preg_replace('/(soccer)|(jerseys?)|(football)|(\*)/i','',$crawlItem['name']),'utf-8');
			$hits=$index->find($query);
			if(count($hits)==0){
				$query=Zend_Search_Lucene_Search_QueryParser::parse(preg_replace('/(\*)/i','',$crawlItem['name']),'utf-8');
				$hits=$index->find($query);
			}
			$myHits=array();
			foreach($hits as $hit){
				if(!$maxScore){
					$maxScore = $hit->score;
				}
				$newHits=new stdClass();
				$newHits->PID=$hit->PID;
				$myHits[]=$newHits;
				unset($newHits);
			}
			$myCache->save($myHits,$cacheId);
		}else{
			$hits=$result;
		}
		$PIDS = array();
		foreach ($hits as $hit)
		{
			$PIDS[] = $hit->PID;
		}
		//L　SEARCH
		if(!empty($PIDS))
		{
			$itemCounts = count($PIDS);
		} else {
			$itemCounts = 0;
		}
		
		$itemArray = array();
		$myCache = Zend_Registry::get('myCache');
		$itemMap = CCache::getCombinlistItemMap();
		for($i=0;$i<10;$i++){
			if($i<$itemCounts){
				array_push($itemArray,$itemMap[$PIDS[$i]]);
			}
		}
		
		$hotItemArray = CCache::getHotItems();
		$leftproducts = array();
		if(count($itemArray) >= 2){
			$leftproducts= array($itemArray[0],$itemArray[1]);
			CMd5cmn::$showNumber = 3;
			$leftproducts = array_merge($leftproducts,CMd5cmn::fakeShuffleArray($hotItemArray,$cacheId));
		}else{
			CMd5cmn::$showNumber = 5;
			$leftproducts = array_merge($leftproducts,CMd5cmn::fakeShuffleArray($hotItemArray,$cacheId));
		}
		$this->view->leftproducts = $leftproducts;
		
		preg_match("/(\d+(\.\d+)?)/",$crawlItem['price'],$priceMatches);
		$this->view->onlyPrice = $priceMatches[0];
		
		$this->view->itemArray = $itemArray;
		
		$this->view->webSiteTitle = $crawlItem['name'];
        $this->view->webSiteDescription = str_replace("\"","",$crawlItem['description']);
        $this->view->webSiteKeywords = $crawlItem['name'];
        
        $date_1=date('Y-m-d');   
		$date_2="2012-09-10"; 
		$d1=strtotime($date_1);   
		$d2=strtotime($date_2);
		$days=round(($d1-$d2)/3600/24); 
		$myrandom = new CMyRandom();
        $peopleCount = (int)($myrandom->getRandomNumber($crawlItem['name'].date('Y-m-d'),50))+$days;
        $this->view->peopleCount=$peopleCount;
        $this->view->peopleCount=$peopleCount;
        $this->view->maxScore = $maxScore;
        
        /*属性筛选*/
		$attr = new CAttr();
        $categoryAttr = $attr->getByType(1);	
        $brandAttr = $attr->getByType(2);	
        $playerAttr = $attr->getByType(3);
        
        $this->view->categoryAttr=$categoryAttr;
        $this->view->brandAttr=$brandAttr;
        $this->view->playerAttr = $playerAttr;
        
        $this->view->isshowchoose = 1;
        
        if($maxScore < 0.9){
	        $search = new CSearch();
			$cresult = $search->searchCrawlAny($crawlItem['name'],10);	
			
			$myLikeCrawlItemArray = array();
			if(count($cresult)>5){ 
				if(is_array($cresult)){
					foreach ($cresult as $v) {
						if($v!=$crawlItem['id']){
							array_push($myLikeCrawlItemArray,$crawl->getCrawlItem($v));		
						}
					}
				}
				if(count($itemArray) >= 1){
					$myLikeCrawlItemArray = array_merge(array($itemArray[0]),$myLikeCrawlItemArray);
				}
			}else{
				$myLikeCrawlItemArray = $itemArray;
			}
		}else{
			$where=R_PRE."items.flid = ".$itemArray[0]['flid']." and is_showed=1 and zcshop_products.onsales=0";
			$itemShow=new CItemShow();
            $itemShow->setType('product');
            $itemShow->setWhere($where);
            $itemShow->setFromTo(array('counts'=>10,'from'=>0));
            $myLikeCrawlItemArray = $itemShow->getAllItems();
			$myLikeCrawlItemArray = array_merge(array($itemArray[0]),$myLikeCrawlItemArray);
		}
		$this->view->myLikeCrawlItemArray = $myLikeCrawlItemArray;
	}
	
}
